<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row
          class="opeate-tools"
          type="flex"
          justify="end"
        >
          <el-button size="mini" type="primary" @click="add">添加员工</el-button>
          <el-button size="mini">excel导入</el-button>
          <el-button size="mini" @click="exportData">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template v-slot="{row, index}">
              <el-button type="text" @click="edit(row.id)">查看</el-button>
              <el-button type="text" @click="addRole(row.id)">角色</el-button>
              <el-popconfirm style="margin-left: 10px" title="确定删除该行数据吗？" @onConfirm="del(row.id)">
                <el-button slot="reference" type="text" @click="showPop(row, index)">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
          ...
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>

      </div>
    </div>
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-co l>
          <el-button type="primary" size="mini" @click="submitRole">确定</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </el-co>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { transformTreeData } from '@/utils/index'
import { departmentList } from '@/api/department'
import { getEmployeeList, assignRole, getEmployeDetail } from '@/api/employee'
import FileSaver from 'file-saver'
import { exportEmployeeList, getEnableRoleList } from '@/api/employee'
export default {
  name: 'Employee',
  data() {
    return {
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 5,
        keyword: '' // 模糊搜索字段
      },
      total: 0, // 记录员工的总数
      list: [],
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [],
      currentUserId: null

    }
  },
  created() {
    this.getDepartment()
    // 获取员工列表
    this.getEmployeeList2()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = transformTreeData(await departmentList(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList2()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList2()
    },
    // 获取员工列表的方法
    async getEmployeeList2() {
      const { rows, total } = await getEmployeeList(this.queryParams) // 获取 total
      this.list = rows
      this.total = total // 更新 total
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList2() // 查询数据
    },
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList2()
      }, 300)
      console.log(140, '触发了')
    },
    async  exportData() {
      console.log(151, '触发了')
      const res = await exportEmployeeList()
      console.log(res, 152)
      FileSaver.saveAs(res, '导出数据')
    },
    // 点击角色按钮弹出层
    async addRole(id) {
      this.showRoleDialog = true
      this.currentUserId = id

      this.roleList = await getEnableRoleList()
      const { roleIds } = await getEmployeDetail(id)
      this.roleIds = roleIds
      console.log(this.currentUserId, this.roleIds, 194)
    },
    async submitRole() {
      await assignRole(
        {
          id: this.currentUserId,
          roleIds: this.roleIds
        }
      )
      this.$message.success('添加成功')
      this.showRoleDialog = false
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
    .el-button {
  transition: all 0.3s ease; // 添加过渡动画，使效果更平滑

}

  }
}

</style>
